<?php
/**
 * @file WCSessionKeep.php
 * @author Alejandro Dario Simi
 * @date $Date: 2013-05-13 04:08:49 +0000 (Mon, 13 May 2013) $
 *
 * $Id: WCSessionKeep.php 64 2013-05-13 04:08:49Z daemonraco@gmail.com $
 * $URL: http://wcomix.googlecode.com/svn/tags/wcomix-1.0-BETA1/includes/security/WCSessionKeep.php $
 */

/**
 * @class WCSessionKeep
 */
class WCSessionKeep extends WCTableRepresentation {
	protected	$_PropertiesReadOnly	= array("id");
	protected	$_PropertiesPrefix	= "skp_";
	protected	$_PropertiesTable	= "session_keeps";
	protected	$_PropertiesAutoSet	= ", skp_timestamp = sysdate()";

	//
	// Public methods
	/**
	* @return WCUser
	*/
	public function lastUser() {
		$out = null;

		if(isset($_COOKIE[WC_COOKIE_KEEPME_USER])) {
			$out = new WCUser();
			$out->load($_COOKIE[WC_COOKIE_KEEPME_USER]);
			if(!$out->ok()) {
				$out = null;
			}
		}		
		
		return $out;
		}
	public function loadByCookies() {
		$this->_ok	= false;
		$this->_info	= array();

		$ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : "unknown";

		$stmt	= null;
		$stmtId	= __CLASS__."::".__FUNCTION__;
		if($this->_db->has($stmtId)) {
			$stmt = $this->_db->get($stmtId);
		} else {
			$query = "select  *\n";
			$query.= "from    {$this->_dbprefix}session_keeps\n";
			$query.= "where   skp_user = :user\n";
			$query.= " and    skp_ip   = :ip\n";

			$stmt = $this->_db->prepare($stmtId, $query);
		}

		$params = array(
				":user"	=> @$_COOKIE[WC_COOKIE_KEEPME_USER],
				":ip"	=> $ip
		);

		if($stmt->execute($params)) {
			foreach($stmt->fetchAll() as $row) {
				if($row["skp_code"] == WCSessionKeep::CodeGenertor($row["skp_salt"])) {
					$this->load($row["skp_id"]);
					break;
				}
			}
		}

		return $this->ok();
	}
	public function updateCookies() {
		if($this->ok()) {
			$lifetime = time() + (86400 * 7);

			setcookie(WC_COOKIE_KEEPME_USER, $this->user, $lifetime);
			setcookie(WC_COOKIE_KEEPME_HASH, $this->code, $lifetime);

			$aux = new WCUser();
			$aux->load($this->user);
			if($aux->ok()) {
				setcookie(WC_COOKIE_KEEPME_NAME, $aux->name(), $lifetime);
			}
			unset($aux);
		}
	}

	//
	// Protected methods

	//
	// Public class methods
	public static function CodeGenertor($salt) {
		$ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : "unknown";

		$code = $salt.$ip.$salt.$_SERVER["HTTP_USER_AGENT"].$salt;

		return md5($code);
	}
}
?>